<template>
  <div class="box" ref="targetElement">
    <div class="search-box" ref="searchBox">
      <div class="search-top-box">
        <div class="search-top-left-box">
          <el-form label-width="110px" ref="div" :inline="true" :model="formSearch" @submit.native.prevent
            class="demo-form-inline">
            <el-form-item label="项目名称">
              <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.project_name"
                placeholder="输入项目名称"></el-input>
            </el-form-item>
            <el-form-item label="项目品牌">
              <el-select filterable @change="onSearch(1)" clearable class="form-width" v-model="formSearch.brand_id"
                placeholder="选择项目品牌">
                <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="项目编号">
              <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.project_number"
                placeholder="输入项目编号"></el-input>
            </el-form-item>
            <el-form-item label="项目类型">
              <el-select filterable @change="onSearch(1)" clearable class="form-width" v-model="formSearch.store_type_id"
                placeholder="选择项目类型">
                <el-option v-for="item in storeTypeList" :key="item.id" :label="item.store_type_name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <template v-if="moreSearchShow">
              <el-form-item label="勘场类型">
                <el-select filterable @change="onSearch(1)" clearable class="form-width" v-model="formSearch.survey_site"
                  placeholder="选择勘场类型">
                  <el-option label="无需勘场" :value="1"></el-option>
                  <el-option label="实地勘场" :value="2"></el-option>
                  <el-option label="勘场出图" :value="3"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="综合平均评分">
                <el-select filterable @change="onSearch(1)" clearable class="form-width" v-model="formSearch.overall_rating"
                  placeholder="选择综合平均评分">
                  <el-option label="1分" :value="1"></el-option>
                  <el-option label="2分" :value="2"></el-option>
                  <el-option label="3分" :value="3"></el-option>
                  <el-option label="4分" :value="4"></el-option>
                  <el-option label="5分" :value="5"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-form>
        </div>
        <div class="search-top-right-box">
          <p @click="moreSearchFunc">
            {{ moreSearchShow ? "收起" : "展开"
            }}<i :class="moreSearchShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
              "></i>
          </p>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="primary" @click="exportVisible = true" :disabled="tableData.length == 0"
            v-if="$isPer(permission, ['sale_exportEvaluationExcel'])">导出项目评分列表</el-button>
        </div>
      </div>
    </div>
    <!-- table -->
    <div class="page-list" ref="pageList">
      <div class="table-box" v-loading="pageLoading">
        <el-table border :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="tableData" height="100%">
          <el-table-column min-width="140px" prop="" label="ID" fixed="left">
            <template slot-scope="scope">
              {{ $assemblyListNo('XMPF', scope.row.id) }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('pf_xmbh')" min-width="130px" fixed="left" prop="project_number"
            label="项目编号" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.project_number }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('pf_xmmc')" min-width="180px" fixed="left" prop="project_name"
            label="项目名称" show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('pf_xmpp')" min-width="120px" fixed="left" prop="brand_name"
            label="项目品牌" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-tag :color="`${scope.row.brand_colour}`" style="color: #ffffff;">
                {{ scope.row.brand_name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('pf_xmlx')" min-width="120px" prop="store_type_name" label="项目类型"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.store_type_name || '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('pf_kclx')" min-width="120px" prop="survey_site" label="勘场类型"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.survey_site == 1">无需勘场</span>
              <span v-if="scope.row.survey_site == 2">实地勘场</span>
              <span v-if="scope.row.survey_site == 3">勘场出图</span>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('pf_zhpjpf')" min-width="120px" prop="overall_rating" label="综合平均评分"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.overall_rating ? scope.row.overall_rating + '分' : '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('pf_xmpf')" min-width="200px" prop="" label="项目评分">
            <template slot-scope="scope">
              <div v-if="scope.row.evaluation_content.length == 0">--</div>
              <div v-else class="row-box" :style="scope.row.is_info ? 'padding-bottom: 20px;' : ''">
                <div v-if="!scope.row.is_info" class="row-open" @click.stop="scope.row.is_info = true">查看 <i
                    class="el-icon-arrow-down"></i></div>
                <template v-else>
                  <div class="row-item" v-for="(item, idx) in scope.row.evaluation_content" :key="idx">
                    <div>{{ item.name }}</div>
                    <div style="border-left: 1px solid #f5f7fa;">{{ item.score }}分</div>
                  </div>
                  <div class="row-close" @click.stop="scope.row.is_info = false"><i class="el-icon-arrow-up"></i></div>
                </template>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-footer">
        <el-pagination class="el-pagination" @current-change="handleCurrentChange" :current-page="page" :page-size="num"
          @size-change="handleSizeChange" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
    <!-- 导出项目评分列表 -->
    <el-dialog :modal-append-to-body="false" title="导出项目评分字段选择" :visible.sync="exportVisible" width="680px"
      :before-close="exportCloseFunc">
      <el-checkbox class="checkbox-item" v-model="allChecked" @change="allCheckedChangeFunc">全选</el-checkbox>
      <div v-loading="exportLoading">
        <div class="export-scroll">
          <el-checkbox-group v-model="exportrVal">
            <el-checkbox class="checkbox-item" v-for="(item, index) in exportArr" :key="index" :label="item.label"
              border></el-checkbox>
          </el-checkbox-group>
        </div>
        <p v-if="exportUrl">导出文件链接：<el-button @click="$openUrlFunc(exportUrl[0])" type="text">{{
          exportUrl[1]
            }}</el-button></p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="exportSubmitFunc">提交</el-button>
        <el-button @click="exportCloseFunc">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import saleApi from '@/api/saleApi';
import brandApi from '@/api/brandApi';
import storeTypeApi from '@/api/storeTypeApi';
import { exportEvaluationFideldArr } from '@/utils/exportField'
export default {
  name: "projectRating",
  data() {
    return {
      // 导出用户列表
      allChecked: false,//是否全选字段
      exportLoading: false,//导出loading
      exportVisible: false,//导出弹窗
      exportUrl: '',//导出url
      exportrVal: [],//导出勾选字段
      exportArr: exportEvaluationFideldArr,//导出字段数组


      tableData: [],
      formSearch: {},
      moreSearchShow: false,
      page: 1,
      num: 10,
      total: 0,
      pageLoading: false,
      brandList: [],
      storeTypeList: [],
      permission: [],//操作权限
    };
  },
  watch: {},
  computed: {
  },
  activated() {
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.onSearch();
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  deactivated() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  mounted() {
    this.handleResize();
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    // 操作权限
    this.$getHtmlAuthority(this.$route.path).then(res => {
      console.log(res, "getHtmlAuthority");
      this.permission = res.data.permission;
    })
    this.hrefQueryFunc(() => {
      this.getEvaluationList();
      this.getBrandList();
      this.getStoreTypeList();
    })
  },
  methods: {
    handleResize() {
      const target = this.$refs.targetElement;
      const searchBox = this.$refs.searchBox;
      const pageList = this.$refs.pageList;
      // 创建 ResizeObserver 实例
      const resizeObserver = new ResizeObserver(entries => {
        setTimeout(() => {
          console.log('元素变为:', searchBox.offsetHeight);
          // searchBox.offsetHeight + 'px'
          pageList.style.height = 'calc(100% - ' + (searchBox.offsetHeight + 15) + 'px)';
        }, 0);
      });
      // 开始观察目标元素
      resizeObserver.observe(target);

      // 存储 resizeObserver 实例，以便在组件销毁时停止观察
      this.resizeObserver = resizeObserver;
    },
    // 跳转判断的
    hrefQueryFunc(cb) {
      let query = this.$route.query;
      if (JSON.stringify(query) != "{}") {
        this.formSearch.project_name = query.project_name || '';//筛选项目名
      }
      cb && cb();
    },
    // 导出列表确认
    exportSubmitFunc() {
      let exportrVal = this.exportrVal;//已勾选
      let exportArr = this.exportArr;//所有字段
      let formSearch = this.formSearch;//列表筛选项
      if (!exportrVal.length) {
        this.$message({
          type: 'warning',
          message: "请勾选需要导出的字段"
        })
        return;
      }
      let field_list = [];//提交列表
      exportrVal.forEach(item => {
        let index = exportArr.findIndex(child => {
          return item == child.label;
        })
        if (index != -1) {
          field_list.push(exportArr[index].value);
        }
      })
      this.exportEvaluationExcel({
        field_list,
        project_name: formSearch.project_name || '',
        project_number: formSearch.project_number || '',
        brand_id: formSearch.brand_id || '',
        store_type_id: formSearch.store_type_id || '',
        survey_site: formSearch.survey_site || '',
        overall_rating: formSearch.overall_rating || '',
      })
    },
    exportEvaluationExcel(obj) {
      this.exportLoading = true;
      saleApi.exportEvaluationExcel(obj).then(res => {
        console.log(res, "导出项目评分列表")
        this.exportLoading = false;
        if (res.code == 200) {
          this.exportUrl = res.data;
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
    // 导出字段全选
    allCheckedChangeFunc(e) {
      let exportrVal = [];
      console.log(e)
      let exportArr = this.exportArr;
      if (e) {
        exportArr.forEach(item => {
          exportrVal.push(item.label);
        })
        this.exportrVal = exportrVal//已选择字段
      } else {
        this.exportrVal = exportrVal//已选择字段
      }
    },
    // 关闭导出弹窗
    exportCloseFunc() {
      this.exportVisible = false;
      this.allChecked = false;
      this.exportrVal = [];
      this.exportUrl = '';
    },
    // 品牌列表
    getBrandList() {
      brandApi
        .getBrandList({
          page: 1,
          num: 9999,
          keyword: "",
        })
        .then((res) => {
          console.log(res, "品牌列表");
          if (res.code == 200) {
            this.brandList = res.data.list;
          }
        })
        .catch(() => { });
    },
    // 门店类型列表
    getStoreTypeList() {
      storeTypeApi.getStoreTypeList({
        page: 1,
        num: 999
      }).then(res => {
        console.log(res, "门店类型列表")
        if (res.code == 200) {
          this.storeTypeList = res.data.list;
        }
      })
    },
    // 评分列表
    getEvaluationList() {
      let formSearch = this.formSearch;
      this.pageLoading = true;
      saleApi.getEvaluationList({
        page: this.page,
        num: this.num,
        project_name: formSearch.project_name || '',
        project_number: formSearch.project_number || '',
        brand_id: formSearch.brand_id || '',
        store_type_id: formSearch.store_type_id || '',
        survey_site: formSearch.survey_site || '',
        overall_rating: formSearch.overall_rating || '',
      }).then(res => {
        console.log(res, "评分列表")
        this.pageLoading = false;
        if (res.code == 200) {
          res.data.list.forEach(item => {
            item.is_info = false
            item.evaluation_content = JSON.parse(item.evaluation_content);
          })
          this.tableData = res.data.list;
          this.total = res.data.max;
        }
      })
    },
    // 单页数据量修改
    handleSizeChange(e) {
      this.num = e;
      this.onSearch(1);
    },
    // 搜索
    onSearch(page) {
      this.page = typeof page == 'number' ? page : this.page;
      this.getEvaluationList();
    },
    // 翻页
    handleCurrentChange(page) {
      this.onSearch(page);
    },
    moreSearchFunc() {
      this.moreSearchShow = !this.moreSearchShow;
      this.$nextTick(() => {
        this.handleResize();
      })
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
@import '@/styles/listPage.scss'
</style>=